#ifndef ROUND_ROBIN_HPP
#define ROUND_ROBIN_HPP

#include <vector>
#include <mutex>

#include "./LoadBalancePolicyIface.h"

namespace LoadBalance
{
    template <typename T>
    class RoundRobin : public LoadBalancePolicyIface<T>
    {
    public:
        explicit RoundRobin(const std::vector<T> &nodes) : nodes_(nodes)
        {
        }

        T getNext() override
        {
            std::lock_guard<std::mutex> lock(this->mtx_);

            if (this->nodes_.empty()) // 注意错误处理
            {
                return T{};
            }

            T nextNode = this->nodes_[this->curIdx_];
            this->curIdx_ = (this->curIdx_ + 1) % this->nodes_.size(); // 注意循环回绕
            return nextNode;
        }

    private:
        std::vector<T> nodes_;

        size_t curIdx_ = 0;
        std::mutex mtx_; // 注意线程安全
    };
} // LoadBalance

#endif // ROUND_ROBIN_HPP